import axios, {AxiosInstance} from "axios";
import {Toast} from "vant";

const isDev = process.env.NODE_ENV === 'development';
const myAxios: AxiosInstance = axios.create({
    //线下localhost，线上服务器ip
    baseURL: isDev ? 'http://localhost:8080/api' : 'http://47.95.17.95:8080/api'
    /*baseURL: 'http://localhost:8080/api'*/
});

myAxios.defaults.withCredentials = true; //设置为true，向后端发送请求携带上我的凭证

// 添加请求拦截器
myAxios.interceptors.request.use(function (config) {

     if (localStorage.getItem("userId")) { // 确保localStorage有一个id属性
        config.headers['userId'] = localStorage.getItem("userId");
    }

    //console.log("发送请求--->", config);
    // Do something before request is sent
    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});


// 添加响应拦截器
myAxios.interceptors.response.use(function (response) {
    //console.log("<---收到响应",response);
    // Do something with response data

    const data = response.data;

    //console.log("收到的数据",data);
    if (data?.code === 40100) {
        Toast("未登录")
        // 跳转到登录页
        const redirectUrl = window.location.href
        window.location.href = `/user/login?redirect=${redirectUrl}`
    }

    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return data;
}, function (error) {
    // Do something with response error
    return Promise.reject(error);
});
export default myAxios;
